import react from "@vitejs/plugin-react"
import { existsSync, readFileSync, readdirSync } from "fs"
import { join, relative, resolve } from "path"
import { ProxyOptions, defineConfig } from "vite"
import { nodePolyfills } from "vite-plugin-node-polyfills"
import basicSsl from "@vitejs/plugin-basic-ssl"
import ProxyConfig from "./viteConfig/proxy"
const API_ENV = process.env.API_ENV || "prod"
const Key = "whzhuke"
const isDev = process.env.NODE_ENV === "development"
const appPath = process.cwd()
const root = join(appPath, "../")
const packagesPath = join(root, "./packages")
const isProd = API_ENV === "prod"
function buildProxy() {
  const proxyList = {} as Record<string, string | ProxyOptions>
  Object.keys(ProxyConfig).forEach(it => {
    proxyList[`/${it}/`] = {
      target: ProxyConfig[it][API_ENV],
      changeOrigin: true,
      rewrite: path => path.replace(`/${it}/`, "/"),
      bypass(req, res, options) {}
    }
  })
  return proxyList
}

const copyPath: any[] = []

function getPackageS() {
  const result = {
    "@/": "/src/"
  }
  const list = readdirSync(packagesPath)
  list.forEach(m => {
    const packageConfig = resolve(packagesPath, `${m}/package.json`)
    if (existsSync(packageConfig)) {
      const { typings, main, module } = JSON.parse(readFileSync(resolve(packagesPath, `${m}/package.json`)).toString())
      let entry = "src/index.ts"
      if (!!typings && existsSync(resolve(packagesPath, m, typings))) {
        entry = typings
      }
      if (main && existsSync(resolve(packagesPath, m, main))) {
        entry = main
      }
      if (module && existsSync(resolve(packagesPath, m, module))) {
        entry = module
      }

      result[`@${Key}/${m}`] = resolve(packagesPath, m, entry)
      result[`@${Key}/${m}/`] = resolve(packagesPath, `${m}/`)
      const publicPath = resolve(packagesPath, `${m}/public`)
      if (existsSync(publicPath)) {
        const relativePath = relative(appPath, publicPath)
        copyPath.push({
          from: relativePath,
          to: `./${m}`
        })
      }
    }
  })
  return result
}

export default defineConfig({
  base: "/",

  plugins: [
    react({
      babel: {
        plugins: [["@babel/plugin-proposal-decorators", { legacy: !0 }]]
      }
    }),
    basicSsl(),
    nodePolyfills()
  ],
  define: {
    PDFJSDev:1,
    nodeDev: isDev,
    API_ENV: JSON.stringify(API_ENV),
    HOST_ENV: (data => {
      return (e => {
        for (let key in data) {
          e[key] = (item => ({ [API_ENV]: item[API_ENV] }))(data[key])
        }
        return e
      })({})
    })(ProxyConfig)
  },
  server: {
    host: "0.0.0.0",
    proxy: buildProxy(),
    cors: {
      origin: true
    }
  },
  build: {
    minify: "esbuild",
    rollupOptions: {
      output: {
        chunkFileNames: "ruler3D-[hash].js",
        experimentalMinChunkSize: 10000
      }
    }
  },

  resolve: {
    alias: getPackageS(),
    preserveSymlinks: true
  }
})
